#include "rename.h"
#include "kmglang_en.h"

struct RenameCtx 
{
	IPTLayer_Form *form;
	IPTLayer_StaticCtrl *staticCtrl;
	IPTLayer_TextEntryCtrl *textEntry;
	NodeFile *node;
};

boolean FormHandleEvent(void*data, AEEEvent evt, uint16 wParam, uint32 dwParam)
{
	MGallery* me = data;

	if(wParam == AVK_SOFT1 && evt == EVT_KEY){
		AlertDesc alert = {0, IDS_RENAME, IDS_MSG_FILE_RENAMED, 0};
		alert.resName = me->resFileName;
		IPTLAYER_MakeAlert(me->ptl, &alert, NULL, NULL);
		Rename_Destroy(me);
		return TRUE;
	}

    return IPTLAYER_FormHandleEvent(me->ptl, me->rename->form, evt, wParam, dwParam);
}

void Rename_Create(MGallery* me, NodeFile* node)
{
	if(me->rename)
		Rename_Destroy(me);
	
	me->rename = MALLOCREC(RenameCtx);
	if(!me->rename)
		return;

	me->rename->node = node;
	
	IPTLAYER_FormCreate(me->ptl, &me->rename->form, FormHandleEvent, NULL, IPTLAYER_NORMAL_BASE);
	IPTLAYER_StaticCreateEx(me->ptl,  me->rename->form, &me->rename->staticCtrl, 0);
	IPTLAYER_TextEntryCreateNew(me->ptl, me->rename->form, &me->rename->textEntry, 0, 1, 4, 32);
	if(!me->rename->form || !me->rename->staticCtrl || !me->rename->textEntry){
		Rename_Destroy(me);
		return;
	}
		

	IPTLAYER_StaticSetTextByID(me->ptl, me->rename->staticCtrl, me->resFileName, 0, IDS_NAME);
	IPTLAYER_CtrlAddToForm(me->ptl, me->rename->staticCtrl, NULL, TRUE);

	IPTLAYER_TextEntrySetIMode(me->ptl, me->rename->textEntry, TN_IMODE_NORMAL_SYMBOL);
	IPTLAYER_TextEntrySetText(me->ptl, me->rename->textEntry, node->base.nodeName);
	IPTLAYER_CtrlAddToForm(me->ptl, me->rename->textEntry, NULL, TRUE);

	IPTLAYER_TitleAdd(me->ptl, me->rename->form, me->resFileName, IDS_RENAME, NULL);
	IPTLAYER_SoftKeyAdd(me->ptl, me->rename->form, me->resFileName, IDS_SAVE, IDS_OPTIONS);
	
	IPTLAYER_FormShow(me->ptl, me->rename->form, TRUE, IPTLAYER_NORMAL_BASE);
}

void Rename_Destroy(MGallery* me)
{
	if(!me->rename)
		return;

	if(me->rename->staticCtrl){
		IPTLAYER_StaticDestroy(me->ptl, me->rename->staticCtrl);
		me->rename->staticCtrl = NULL;
	}

	if(me->rename->textEntry){
		IPTLAYER_TextEntryDestroy(me->ptl, me->rename->textEntry);
		me->rename->textEntry = NULL;
	}

	if(me->rename->form){
		IPTLAYER_FormDestroy(me->ptl, me->rename->form);
		me->rename->form = NULL;
	}
}
